from django.shortcuts import render
from .models import *
from rest_framework.response import Response
from rest_framework.views import APIView
# Create your views here.

class KindView(APIView):
    def get(self,request):
        kind_data = Kind.objects.all()
        kind_list=[]
        for i in kind_data:
            kind_list.append({
                "id":i.id,
                "name":i.name
            })
        return Response({"code":200,"msg":"获取所有种类成功","kind":kind_list})

class SpView(APIView):
    def get(self,request,k_id):
        sp_data = SP.objects.filter(kind_id=k_id)
        sp_list = []
        for i in sp_data:
            sp_list.append({
                "id":i.id,
                "sname":i.sname,
                "xs":i.xs,
                "money":i.money,
                "kind":i.kind.id,
                "img":i.img,
            })
        return Response({"code":200,"msg":"获取单个数据成功"})

class AddView(APIView):
    def post(self,request):
        name = request.data.get("name")
        Kind.objects.create(
            name=name
        )
        return Response({"code":200,"msg":"添加种类数据成功"})

class AddView1(APIView):
    def post(self,request):
        img = request.data.get("img")
        sname = request.data.get("sname")
        xs = request.data.get("xs")
        money = request.data.get("money")
        kind = request.data.get("kind_id")
        SP.objects.create(
            img=img,
            sname=sname,
            xs=xs,
            money=money,
            kind_id=kind
        )
        return Response({"code":200,"msg":"添加数据成功"})



class DelView(APIView):
    def delete(self,reqiest,id):
        Kind.objects.filter(id=id).delete()
        return Response({"code": 200, "msg": "删除数据成功"})


class PutView(APIView):
    def put(self,request,id):
        name = request.data.get("name")
        Kind.objects.filter(id=id).update(
            name=name
        )
        return Response({"code": 200, "msg": "修改数据成功"})